import { contextBridge } from "electron";
import { electronAPI } from "@electron-toolkit/preload";
import Electron from "electron";
import ipcRenderer = Electron.ipcRenderer;
import { MsgChannel } from "@common/constants";

const storeApi = {
  get: (key) => ipcRenderer.sendSync(MsgChannel.Store.GET, key),
  getBatch: (keys) => ipcRenderer.sendSync(MsgChannel.Store.GET_BATCH, keys),
  set: (key, value) => ipcRenderer.sendSync(MsgChannel.Store.SET, key, value),
  delete: (key) => ipcRenderer.sendSync(MsgChannel.Store.DELETE, key),
  reset:(key) => ipcRenderer.sendSync(MsgChannel.Store.RESET, key)
};

const menuApi = {
  // 显示右键菜单
  showContextMenu: (menuType, data) => {
    return ipcRenderer.invoke(MsgChannel.Menu.showMenu, menuType, data);
  },

  // 监听菜单操作
  onMenuAction: (callback) => {
    ipcRenderer.on(MsgChannel.Menu.selectMenu, (_, action, data) => {
      callback(action, data);
    });
  },
}

const folderApi = {
  selectFolder:() => {
    return  ipcRenderer.invoke(MsgChannel.Folder.Select);
  },
  openFolder:(folderPath) => {
    return  ipcRenderer.invoke(MsgChannel.Folder.Open, folderPath);
  },
}

const api = {
  onImageMsg: (callback) =>
    ipcRenderer.on(MsgChannel.Image.GET,
      (_, ...args) => callback(...args)),
  onConnect: (callback) =>
    ipcRenderer.on(MsgChannel.Connect,
      (_, ...args) => callback(...args)),
  onDisconnect: (callback) =>
    ipcRenderer.on(MsgChannel.Disconnect,
      (_, ...args) => callback(...args)),

  sendSocketIoMsg:(msg) => {
    return ipcRenderer.invoke(MsgChannel.SendSocketIo,msg);
  }
};

if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld("electron", electronAPI);
    contextBridge.exposeInMainWorld("api", api);
    contextBridge.exposeInMainWorld("localStore", storeApi);
    contextBridge.exposeInMainWorld("menuApi", menuApi);
    contextBridge.exposeInMainWorld("folderApi", folderApi);
  } catch (error) {
    console.error(error);
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI;
  // @ts-ignore (define in dts)
  window.api = api;
  // @ts-ignore (define in dts)
  window.localStore = storeApi;
}
